package com.njworkorder.Utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    private static final String[] hexDigits = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    //这里主要是遍历8个byte，转化为16位进制的字符，即0-F
    private static String byteArrayToHexString(byte[] b) {
        //定义
        StringBuilder resultSb = new StringBuilder();//定义
        for (byte ab : b) {
            resultSb.append(byteToHexString(ab));//定义
        }

        return resultSb.toString();
    }

    //这里是针对单个byte，256的byte通过16拆分为d1和d2
    private static String byteToHexString(byte b) {
        int n = b;//定义
        if (n < 0) {
            n += 256;//定义
        }
        int d1 = n / 16;//定义
        int d2 = n % 16;//定义
        return hexDigits[d1] + hexDigits[d2];
    }

    /**
     * 返回大写MD5
     *
     * @param origin
     * @param charsetname
     * @return
     */
    public static String MD5Encode(String origin, String charsetname, boolean max) {
        //定义
        String resultString = null;
        try {
            resultString = origin;//定义
            MessageDigest md = MessageDigest.getInstance("MD5");//定义
            if (charsetname == null || charsetname.isEmpty()) {
                //定义
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));//定义
            } else {
                //定义
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));//定义
            }
        } catch (Exception exception) {
            exception.printStackTrace();//定义
            return resultString;
        }

        return max ? resultString.toUpperCase() : resultString;
    }




    // MD5 加密方法
    public static String encrypt(String input){
        try {
            MessageDigest md = MessageDigest.getInstance("MD5"); // 创建 MD5 实例
            byte[] messageDigest = md.digest(input.getBytes()); // 获取加密后的字节数组
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b); // 转换为十六进制字符串
                if (hex.length() == 1) hexString.append('0'); // 补零
                hexString.append(hex);
            }
            return hexString.toString(); // 返回十六进制字符串
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 加密失败", e);
        }
    }
}
